using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Work.API.Applications.Read.Commands;
using Work.API.Dtos.DrugManagement;
using Work.Domain.DrugManage;
using Work.ErrorCode;
using Work.Infrastructure.Interfaces;

namespace Work.API.Applications.Read.CommandHandlers
{
    /// <summary>
    /// 获取检药单列表处理器（用于查看检药单模块）
    /// </summary>
    public class GetInspectionListQueryHandler : IRequestHandler<GetInspectionListQuery, ApiResult<List<InspectionListDto>>>
    {
        private readonly IBaseRepository<DrugInspection> _inspectionRepo;
        private readonly IMapper _mapper;

        public GetInspectionListQueryHandler(IBaseRepository<DrugInspection> inspectionRepo, IMapper mapper)
        {
            _inspectionRepo = inspectionRepo;
            _mapper = mapper;
        }

        public async Task<ApiResult<List<InspectionListDto>>> Handle(GetInspectionListQuery request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<InspectionListDto>>();

            try
            {
                var query = _inspectionRepo.GetAll()
                    .Include(di => di.Patient)
                    .AsNoTracking();

                // 处理时间筛选类型（今天/本周/本月/今年/全部）
                DateTime? startDate = request.StartDate;
                DateTime? endDate = request.EndDate;

                if (!string.IsNullOrWhiteSpace(request.TimeFilterType))
                {
                    var now = DateTime.Now;
                    switch (request.TimeFilterType)
                    {
                        case "今天":
                            startDate = now.Date;
                            endDate = now.Date.AddDays(1).AddSeconds(-1);
                            break;
                        case "本周":
                            var dayOfWeek = (int)now.DayOfWeek;
                            dayOfWeek = dayOfWeek == 0 ? 7 : dayOfWeek; // 周日转为7
                            startDate = now.Date.AddDays(1 - dayOfWeek);
                            endDate = startDate.Value.AddDays(7).AddSeconds(-1);
                            break;
                        case "本月":
                            startDate = new DateTime(now.Year, now.Month, 1);
                            endDate = startDate.Value.AddMonths(1).AddSeconds(-1);
                            break;
                        case "今年":
                            startDate = new DateTime(now.Year, 1, 1);
                            endDate = startDate.Value.AddYears(1).AddSeconds(-1);
                            break;
                        case "全部":
                        default:
                            // 不设置日期范围，查询全部
                            break;
                    }
                }

                // 动态构建查询条件
                if (!string.IsNullOrWhiteSpace(request.RegistrationNum))
                {
                    query = query.Where(di => di.RegistrationNum == request.RegistrationNum);
                }

                if (!string.IsNullOrWhiteSpace(request.PatientName))
                {
                    query = query.Where(di => di.PatientName != null && di.PatientName.Contains(request.PatientName));
                }

                if (!string.IsNullOrWhiteSpace(request.InspectionStatus))
                {
                    query = query.Where(di => di.InspectionStatus == request.InspectionStatus);
                }

                if (request.IsDispensed.HasValue)
                {
                    query = query.Where(di => di.IsDispensed == request.IsDispensed.Value);
                }

                if (startDate.HasValue)
                {
                    query = query.Where(di => di.CreateTime >= startDate.Value);
                }

                if (endDate.HasValue)
                {
                    query = query.Where(di => di.CreateTime <= endDate.Value);
                }

                // 默认只查询未发药的检药单（如果IsDispensed没有指定）
                if (!request.IsDispensed.HasValue)
                {
                    query = query.Where(di => di.IsDispensed == false);
                }

                // 按创建时间倒序排列
                var inspections = await query
                    .OrderByDescending(di => di.CreateTime)
                    .ToListAsync(cancellationToken);

                // 映射为DTO，并填充患者信息
                var dtoList = new List<InspectionListDto>();
                foreach (var inspection in inspections)
                {
                    var dto = _mapper.Map<InspectionListDto>(inspection);
                    if (inspection.Patient != null)
                    {
                        dto.Gender = inspection.Patient.Gender;
                        dto.Age = inspection.Patient.Age;
                        dto.IdCard = inspection.Patient.IdCard;
                    }
                    dtoList.Add(dto);
                }

                result.Code = ApiEnum.成功;
                result.Message = "查询成功";
                result.Data = dtoList;
            }
            catch (System.Exception ex)
            {
                result.Code = ApiEnum.失败;
                result.Message = $"查询失败：{ex.Message}";
                result.Data = new List<InspectionListDto>();
            }

            return result;
        }
    }
}

